package main.链表;

import common.ListNode;

/**
 * @author tmh
 * @date 2024/7/20 14:18
 * @description
 */
public class T2两数相加 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //定义一个链表来存储结果
        ListNode result = new ListNode(0);
        //定义一个指针来操作链表
        ListNode current = result;

        int count = 0;
        while (l1 != null || l2 != null || count != 0) {
            int sum = 0;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }

            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            sum += count;
            //判断count的值，sum大于等于10就需要进位
            count = sum >= 10 ? 1 : 0;
            //举例,如果sum为18，那么对应的位置就存8，1就进位了
            current.next = new ListNode(sum - count * 10);
            current = current.next;
        }
        return result.next;
    }
}
